package com.lishe.lishe.lishe.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.lishe.lishe.R;

import java.io.File;
import java.lang.ref.SoftReference;

/**
 * Created by DELL on 2017/11/21.
 */

public class CameraUtils {

    public static final int REQUEST_OPEN_CAMERA=1001;
    public static final int REQUEST_OPEN_CAMERA_AND_SAVE=1002;
    public static final int CLIP_PHOTO_PICTURE=1003;
    public static final int OPEN_ALBUM=1004;

    public static void openCamera(Activity activity) {
        SoftReference<Activity> soft=new SoftReference<Activity>(activity);
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        soft.get().startActivityForResult(intent,REQUEST_OPEN_CAMERA);
    }

    /**
     * 拍照后保存
     * @param activity
     * @param file
     */
    public static void openCamera(Activity activity,File file) {
        SoftReference<Activity> soft=new SoftReference<Activity>(activity);
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri photoUri = Uri.fromFile(file); // 传递路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);// 更改系统默认存储路径
        soft.get().startActivityForResult(intent, REQUEST_OPEN_CAMERA_AND_SAVE);

    }

    /**
     * 取得返回的照片信息并跳转到裁剪界面
     * @param uri 传进返回数据的uri
     裁剪下来的新图片的uri地址
     */
    public static void getClipPhotoByPickPicture(Uri uri,Activity activity) {
        SoftReference<Activity> soft=new SoftReference<Activity>(activity);
        Uri saveUri=null;
        if (uri == null) {
            /**
             *
             */

        } else {
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);// aspectX是宽高的比例，这里设置的是正方形（长宽比为1:1）
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 400); // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputY", 400); //不知怎么了，我设置不能设太大，<640
            intent.putExtra("scale", true);

            if(saveUri==null) {
                saveUri=Uri.fromFile(FileUtils.getClipPhotoByPickPicturePath(activity));
                // return-data为true时,会直接返回bitmap数据,但是大图裁剪时会出现问题,推荐下面为false时的方式
                // return-data为false时,不会返回bitmap,但需要指定一个MediaStore.EXTRA_OUTPUT保存图片uri,即会在内存卡中会保存裁剪后的图片
                // 指定一个MediaStore.EXTRA_OUTPUT保存图片uri，相当于根据uri创建图片保存，需要新传入新uri，否则裁剪图片会覆盖原来图片
            }
            intent.putExtra("return-data", false);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, saveUri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("noFaceDetection", true);
            soft.get().startActivityForResult(intent, CLIP_PHOTO_PICTURE);
        }

    }

    /**
     * 打开系统相册
     * @param activity
     */
    public static void openAlbum(Activity activity) {
        SoftReference<Activity> soft=new SoftReference<Activity>(activity);
        Intent intent=new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        soft.get().startActivityForResult(intent,OPEN_ALBUM);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String handlerImageOnKitKat(Intent data, Activity activity){
        SoftReference<Activity> soft=new SoftReference<Activity>(activity);
        String imagePath=null;
        Uri uri=data.getData();
        if(DocumentsContract.isDocumentUri(soft.get(),uri)){
            //如果是document类型的Uri,则通过document id处理
            String docId= DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id=docId.split(":")[1];//解析出数字格式的id
                String selection=MediaStore.Images.Media._ID+"="+id;
                imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection,soft.get());
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                imagePath=getImagePath(contentUri,null,soft.get());
            }
        }else if("content".equalsIgnoreCase(uri.getScheme())){
            //如果是content类型的URI，则使用普通方式处理
            imagePath=getImagePath(uri,null,soft.get());
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            //如果是file类型的Uri,直接获取图片路径即可
            imagePath=uri.getPath();
        }

        return imagePath;
    }

    public static String getImagePath(Uri uri, String selection,Activity activity) {
        SoftReference<Activity> soft=new SoftReference<Activity>(activity);
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = soft.get().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    /** Receiver扫描更新图库图片 **/

    public static void ScannerByReceiver(Context context,String path) {
        MediaScanner scanner=new MediaScanner(context);
        String[] filePaths=new String[]{path};
        String[] mineTypes=new String[]{MimeTypeMap.getSingleton().getMimeTypeFromExtension("png")};
        scanner.scanFiles(filePaths,mineTypes);
    }
}
